package com.yishe.framework.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.yishe.framework.ui.easyui.TreeNode;

public class TreeUtils<T> {
	private TreeUtils() {}
	
	private static String idFieldName;
	private static String parentIdFieldName;
	private List<TreeNode<T>> tree = null;
	
	public List<TreeNode<T>> getTree() {
		return tree;
	}
	
	public static <T> void getFieldName(List<T> source){
		Type genType = source.getClass().getGenericSuperclass();
		if( !(genType instanceof ParameterizedType) ){
			throw new RuntimeException("请将参数List<T>的泛型补充完整");
		}
		Type param = ((ParameterizedType) genType).getActualTypeArguments()[0];
		Class<T> clazz = (Class<T>) param;
		if(clazz.isAnnotationPresent(TreeConfig.class)){
			TreeConfig treeconf = clazz.getAnnotation(TreeConfig.class);
			idFieldName = treeconf.id();
			parentIdFieldName = treeconf.parentId();
		}else if( clazz.isAnnotationPresent(TreeId.class) && clazz.isAnnotationPresent(TreeParentId.class) ){
			Field[] fields = clazz.getDeclaredFields();
			for(Field f : fields){
				f.getType();
			}
		}
	}
	
	public static <T> List<TreeNode<T>> getTree(List<T> source){

		
		TreeUtils<T> result = new TreeUtils<T>();
		
//		List<T> temp = result.findChildren("-1",temp);
		
		return result.getTree();
	}
	
	public void sort(){
		
	}
	
	/** 
	 * 获取parentId=?的集合
	 * @param parentId
	 * @param all
	 * @return
	 */
	private List<T> findChildren(String parentId, List<T> all) {
		List<T> list = new ArrayList<T>();
		/*for (T c : all) {
			if (parentId.equals(c.getParentId())) {
				list.add(c);
				c.setChildren(findChildren(c.getId(), all));	
			}
		}*/
		return list;
	}
	

	
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.TYPE)
	public static @interface TreeConfig{
		public String id();
		public String parentId();
	}
	
	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public static @interface TreeId{ }

	@Retention(RetentionPolicy.RUNTIME)
	@Target(ElementType.FIELD)
	public static @interface TreeParentId{ }
}
